//
//  AppDelegate.m
//  YouinRTCDemo
//
//  Created by lprison on 2021/9/12.
//

#import "AppDelegate.h"
#import "LiveRoomViewController.h"
#import "LoginViewController.h"
#import "AFNetworking.h"
#import "RYAlertController.h"
#import "LiveListViewController.h"
#import <Bugly/Bugly.h>
@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [Bugly startWithAppId:@"7a21c406aa"];
    [YouinRTCManager shardManager].app_id = @"211533233354404";
    [YouinRTCManager shardManager].app_secret = @"159cddccdc8c6a396c10f3d1afc5483b";
    [[YouinRTCManager shardManager] initEnvWithUser];
    //判断是否升级
    [self updateVersion];
    
    IQKeyboardManager.sharedManager.enable = YES;
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *userInfo = [defaults dictionaryForKey:@"userInfo"];

    // 将时间戳转换为NSDate对象
    NSTimeInterval timestamp = [userInfo[@"exprise_time"] intValue];
    NSDate *exprise_date = [NSDate dateWithTimeIntervalSince1970:timestamp];
    
    // 获取当前日期的NSDate对象
    NSDate *currentDate = [NSDate date];

    if(![Tool strIsNULL:userInfo[@"token"]])
    {
//         使用compare:方法比较两个NSDate对象的大小
        NSComparisonResult result = [exprise_date compare:currentDate];

        // 根据比较结果打印不同的信息
        if (result == NSOrderedAscending) {
            NSLog(@"%@ 早于 %@", exprise_date, currentDate);
            [self loginOutWindowHome];
        }else
        {
            LiveListViewController *listVC = [[LiveListViewController alloc] init];
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:listVC];
            self.window.rootViewController = nav;
        }
    }else{
        [self loginOutWindowHome];
    }
   
    [self.window makeKeyAndVisible];
    
    return YES;
}

-(void)loginOutWindowHome{
    
    LoginViewController *loginVC = [[LoginViewController alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:loginVC];
    self.window.rootViewController = nav;
 }

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    if (self.isFlip) {
        return UIInterfaceOrientationMaskLandscape;
    }
    return UIInterfaceOrientationMaskPortrait;
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
  
    [self updateVersion];
}


#pragma mark - 校验是否升级
- (void)updateVersion{

    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    // 本地版本
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    
    int random = arc4random() % 100000;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 30.0f;
   manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/javascript",@"text/plain", nil];
    
    NSString *urlString = [NSString stringWithFormat:@"https://qncdn.youinsh.cn/ios_version_info/ios_version.json?t=%d",random];
                            

    [manager GET:urlString parameters:nil headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        if (responseObject[@"version_info"]!=nil&&responseObject[@"version_info"]!= NULL) {
            
            NSString *appValue = [NSString stringWithFormat:@"%@",responseObject[@"version_info"][@"version"]];
            
            if ([app_Version compare:appValue options:NSNumericSearch] == NSOrderedDescending)
            {
                NSLog(@"==-----");
            }else
            {    //is_force_update = 1 审核中，= 0 审核后
                if ([[responseObject[@"version_info"] objectForKey:@"is_force_update"] floatValue]==1) {
                    //强制更新
                    [RYAlertController showAlertWithTitle:@"温馨提示" message:@" 【重要版本更新】为了提供更好的直播体验，请您更新最新版，敬请谅解。" appearanceProcess:^(RYAlertController * _Nonnull alertMaker) {
                                                   alertMaker.addActionDefaultTitle(@"更新");
                                               } actionsBlock:^(NSInteger buttonIndex, UIAlertAction * _Nonnull action, RYAlertController * _Nonnull alertSelf) {

                                                   [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://apps.apple.com/cn/app/%E6%9C%89%E5%9B%A0%E7%9B%B4%E6%92%AD/id1601364974"] options:@{} completionHandler:nil];

                                               }];
                }else
                {
//                    非强制升级
                       [RYAlertController showAlertWithTitle:@"温馨提示" message:@"有新版本需要更新!" appearanceProcess:^(RYAlertController * _Nonnull alertMaker) {
                           alertMaker.addActionDefaultTitle(@"取消").addActionDefaultTitle(@"更新");
                       } actionsBlock:^(NSInteger buttonIndex, UIAlertAction * _Nonnull action, RYAlertController * _Nonnull alertSelf) {
                           if (buttonIndex == 1) {

                               [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://apps.apple.com/cn/app/%E6%9C%89%E5%9B%A0%E7%9B%B4%E6%92%AD/id1601364974"] options:@{} completionHandler:nil];
                           }
                       }];

                }
            }
        }
        NSLog(@"=====");
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

@end
